package com.yt.app.h5.filter;

import com.yt.app.core.utils.TokenUtil;
import com.yt.app.h5.exception.AppException;
import com.yt.website.api.interfaces.UserInfoService;
import com.yt.website.api.model.UserInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AppConsumerFilter implements HandlerInterceptor {
	private Log log = LogFactory.getLog(AppConsumerFilter.class);
	@Autowired
	private UserInfoService userInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		log.debug("进入spring mvc拦截器");
		String token = request.getHeader("x-access-token");
		if(token == null){
			token = request.getParameter("token");
		}
		if(token == null){
			throw new AppException("99", "Invalid Token");
		}

		String tokenDetail = new String(Base64Utils.decodeFromUrlSafeString(token), "UTF-8");
		if(!tokenDetail.contains(":")){
			throw new AppException("99", "Invalid Token");
		}

		String[] infos = tokenDetail.split(":");
		Long uid = Long.parseLong(infos[0]);

		UserInfo userInfo = userInfoService.get(uid);
		String newToken = TokenUtil.makeToken(uid, userInfo.getPassword(), userInfo.getUserType());

		if(!newToken.equals(token)) {
			throw new AppException("99", "Invalid Token");
		}

		/* 1.检测用户 */
		return true;
	}

	/**
	 * 获取请求的相对的url
	 * 
	 * @param request
	 * @return
	 */
	private String getContextPath(HttpServletRequest request) {
		String uri = request.getServletPath();
		String pathInfo = request.getPathInfo();
		if (pathInfo != null && pathInfo.length() > 0) {
			uri = uri + pathInfo;
		}
		return uri;
	}
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
}
